package controllers

import (
	"github.com/gin-gonic/gin"
	"shoping.zozoo.net/model"
	"shoping.zozoo.net/params"
	"shoping.zozoo.net/service"
	"shoping.zozoo.net/tool"
	"strconv"
)

type ProductController struct {
	service service.ProductInterface
}

//实例化结构体
func NewProductController(s service.ProductInterface) *ProductController {
	return &ProductController{
		s,
	}
}

//获取产品详情
func (p *ProductController) Get(c *gin.Context) {
	var (
		err     error
		id      int64
		product *model.Product
	)

	if id, err = strconv.ParseInt(c.Param("id"), 10, 64); err != nil {
		tool.ResponseSuccess(c, "参数错误")
		return
	}

	if product, err = p.service.GetProductById(id); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, product)
}

//获取产品列表
func (p *ProductController) List(c *gin.Context) {
	var (
		err  error
		list []*model.Product
	)

	if list, err = p.service.GetAllProduct(); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, list)
}

//删除产品
func (p *ProductController) Del(c *gin.Context) {
	var (
		err error
		id  int64
		ok  bool
	)

	if id, err = strconv.ParseInt(c.Param("id"), 10, 64); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	if ok, err = p.service.DelProductById(id); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	if !ok {
		tool.ResponseError(c, tool.Fail, "删除失败")
		return
	}

	tool.ResponseSuccess(c, "ok")
}

//添加产品
func (p *ProductController) Insert(c *gin.Context) {
	var (
		err   error
		param *params.ProductParam
		id    int64
	)

	param = new(params.ProductParam)

	//参数绑定
	if err = c.ShouldBindJSON(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	if id, err = p.service.InsertProduct(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, id)

}

//秒杀商品
func (p *ProductController) Seckill(c *gin.Context) {
	var (
		param *params.Seckill
		err   error
		order *model.Order
	)

	param = new(params.Seckill)

	//参数验证
	if err = c.ShouldBindJSON(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	if order, err = p.service.Seckill(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, order)
}
